package com.adtech.farmProducts.activities.activity;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.v7.widget.GridLayoutManager;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;

import com.adtech.common.Common;
import com.adtech.common.http.AsyncHttpPostFormData;
import com.adtech.common.http.AsyncHttpResponse;
import com.adtech.common.http.AsyncOkHttpClient;
import com.adtech.common.http.AsyncResponseHandler;
import com.adtech.common.model.RspModel;
import com.adtech.common.widgets.load.LoadFactory;
import com.adtech.common.widgets.load.core.LoadManager;
import com.adtech.common.widgets.load.view.AbsView;
import com.adtech.common.widgets.recycler.RecyclerViewAdapter;
import com.adtech.farmProducts.R;
import com.adtech.farmProducts.adapter.CommodityTypeAdapter;
import com.adtech.farmProducts.adapter.CommodityTypeItemAdapter;
import com.adtech.farmProducts.base.BaseActivity;
import com.adtech.farmProducts.base.BaseNfcActivity;
import com.adtech.farmProducts.model.CommodityType;
import com.adtech.farmProducts.model.CommodityTypeItem;
import com.adtech.farmProducts.widget.ClearTextIconEditText;
import com.adtech.farmProducts.widget.EmptyView;
import com.adtech.farmProducts.widget.ErrorView;
import com.adtech.farmProducts.widget.LoadingView;
import com.google.gson.reflect.TypeToken;

import java.io.IOException;
import java.lang.reflect.Type;
import java.util.List;

import butterknife.BindView;

/**
 * Time:2020/6/29
 * Created by xiaocz
 * Describe 商品类型-选择
 */
public class CommodityTypeActivity extends BaseNfcActivity implements TextWatcher {

    @BindView(R.id.edit_gs_name)
    ClearTextIconEditText edit_gs_name;
    @BindView(R.id.recycler_view)
    RecyclerView mRecyclerView;
    @BindView(R.id.recycler_view_item)
    RecyclerView recycler_view_item;

    /**
     * DATA
     */
    private LoadManager mLoadManager, mLoadManagerItem;
    private CommodityTypeAdapter commodityTypeAdapter;
    private CommodityTypeItemAdapter commodityTypeItemAdapter;

    public static void show(Context context) {
        Intent intent = new Intent(context, CommodityTypeActivity.class);
        context.startActivity(intent);
    }

    @Override
    protected int getLayoutSourceId() {
        return R.layout.activity_commodity_type;
    }


    @Override
    protected void initWidgets() {
        super.initWidgets();
        mLoadManager = LoadFactory.getInstance().register(mRecyclerView, new AbsView.OnReloadListener() {
            @Override
            public void onReload(View view) {
                mLoadManager.showStateView(LoadingView.class);
                queryItem();
            }
        });
        mLoadManagerItem = LoadFactory.getInstance().register(recycler_view_item, new AbsView.OnReloadListener() {
            @Override
            public void onReload(View view) {
                mLoadManagerItem.showStateView(LoadingView.class);
                queryItemType();
            }
        });
        mLoadManagerItem.showSuccessView();
        edit_gs_name.addTextChangedListener(this);
    }


    @Override
    protected void initData() {
        mRecyclerView.setLayoutManager(new LinearLayoutManager(mContext));
        commodityTypeAdapter = new CommodityTypeAdapter(new RecyclerViewAdapter.AdapterListenerImpl<CommodityType>() {
            @Override
            public void onItemClick(RecyclerViewAdapter.ViewHolder<CommodityType> holder, CommodityType data, int position) {
                super.onItemClick(holder, data, position);
                edit_gs_name.setText("");
                productTypeName = "";//清空搜索内容
                for (CommodityType type : commodityTypeAdapter.getDataList()) {
                    type.setCheck(false);
                }
                commodityTypeAdapter.getDataList().get(position).setCheck(true);
                commodityTypeAdapter.notifyDataSetChanged();// 刷新显示
                productItemId = data.getProductItemId();
                queryItemType();
                hideKeyboard();
            }
        });
        mRecyclerView.setAdapter(commodityTypeAdapter);
        recycler_view_item.setLayoutManager(new GridLayoutManager(mContext, 3));
        commodityTypeItemAdapter = new CommodityTypeItemAdapter(new RecyclerViewAdapter.AdapterListenerImpl<CommodityTypeItem>() {
            @Override
            public void onItemClick(RecyclerViewAdapter.ViewHolder<CommodityTypeItem> holder, CommodityTypeItem data) {
                super.onItemClick(holder, data);
                Intent intent = new Intent();
                Bundle bundle = new Bundle();
                bundle.putSerializable("CommodityTypeItem", data);
                intent.putExtras(bundle);
                setResult(200, intent);
                finish();
            }
        });
        recycler_view_item.setAdapter(commodityTypeItemAdapter);
        queryItem();
        super.initData();
    }

    /**
     * 一级分类
     */
    private void queryItem() {
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        okHttpClient.posts(Common.Constant.API_IP + "product/queryItem", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                mLoadManager.showStateView(ErrorView.class);
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                Type type = new TypeToken<RspModel<List<CommodityType>>>() {
                }.getType();
                RspModel<List<CommodityType>> rspModel = getAnalysisBase(mLoadManager, response, type, "一级分类");
                if (rspModel == null) {
                    mLoadManager.showStateView(EmptyView.class);
                    return;
                }
                switch (rspModel.getCode()) {
                    case 1:
                        if (rspModel.getData() != null && !"[]".equals(rspModel.getData().toString())) {
                            CommodityType commodityType = rspModel.getData().get(0);
                            commodityType.setCheck(true);
                            productItemId = commodityType.getProductItemId();
                            commodityTypeAdapter.replace(rspModel.getData());
                            queryItemType();
                        } else {
                            mLoadManager.showStateView(EmptyView.class);
                        }
                        break;
                    default:
                        mLoadManager.showStateView(ErrorView.class);
                        break;
                }
            }
        });
    }

    private long productItemId;
    private String productTypeName;

    private void queryItemType() {
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        asyncHttpPostFormData.addFormData("productItemId", productItemId);
        asyncHttpPostFormData.addFormData("productTypeName", productTypeName);
        okHttpClient.posts(Common.Constant.API_IP + "product/queryType", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                mLoadManagerItem.showStateView(ErrorView.class);
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                Type type = new TypeToken<RspModel<List<CommodityTypeItem>>>() {
                }.getType();
                RspModel<List<CommodityTypeItem>> rspModel = getAnalysisBase(mLoadManagerItem, response, type, "二级分类");
                if (rspModel == null) {
                    mLoadManagerItem.showStateView(EmptyView.class);
                    return;
                }
                switch (rspModel.getCode()) {
                    case 1:
                        if (rspModel.getData() != null && !"[]".equals(rspModel.getData().toString())) {
                            commodityTypeItemAdapter.replace(rspModel.getData());
                        } else {
                            mLoadManagerItem.showStateView(EmptyView.class);
                        }
                        break;
                    default:
                        mLoadManagerItem.showStateView(ErrorView.class);
                        break;
                }
            }
        });
    }

    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {

    }

    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
        String newText = s.toString().trim();
        if (newText.length() > 0) {
            productTypeName = newText;
            queryItemType();
        }
    }

    @Override
    public void afterTextChanged(Editable s) {

    }
}
